package com.itheima.activiti.test;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.*;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.RepositoryService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
public class MyActivitiTest2 {

    @Autowired
    private RepositoryService repositoryService;

    /**
     * 动态构建Bpmn, 完成部署
     */
    @Test
    public void testDynamicDeploy(){
        //1. 构建Process
        Process process = new Process();
        process.setId("myProcess_1");
        process.setName("请假");

        //2. 开始节点
        StartEvent startEvent = new StartEvent();
        startEvent.setId("start_1");
        startEvent.setName("开始流程");


        //绘制连线
        SequenceFlow sf1 = new SequenceFlow();
        sf1.setId("s_1");
        sf1.setSourceRef("start_1");
        sf1.setTargetRef("task_1");


        //3. 用户任务 - 用户申请
        UserTask userTask1 = new UserTask();
        userTask1.setId("task_1");
        userTask1.setName("用户申请");
        userTask1.setAssignee("ITHEIMA");


        //绘制连线
        SequenceFlow sf2 = new SequenceFlow();
        sf2.setId("s_2");
        sf2.setSourceRef("task_1");
        sf2.setTargetRef("task_2");


        //4. 用户任务 - 直属领导审批
        UserTask userTask2 = new UserTask();
        userTask2.setId("task_2");
        userTask2.setName("直属领导审批");
        userTask2.setAssignee("ITCAST");


        //绘制连线
        SequenceFlow sf3 = new SequenceFlow();
        sf3.setId("s_3");
        sf3.setSourceRef("task_2");
        sf3.setTargetRef("end_1");


        //5. 结束节点
        EndEvent endEvent = new EndEvent();
        endEvent.setId("end_1");
        endEvent.setName("结束节点");


        //将各个节点及连线 ---> 封装到 Process
        process.addFlowElement(startEvent);
        process.addFlowElement(sf1);
        process.addFlowElement(userTask1);
        process.addFlowElement(sf2);
        process.addFlowElement(userTask2);
        process.addFlowElement(sf3);
        process.addFlowElement(endEvent);


        //封装BpmnModel
        BpmnModel bpmnModel = new BpmnModel();
        bpmnModel.addProcess(process);


        //部署Bpmn到Activiti ------> 动态部署
        repositoryService.createDeployment()
                .name("请假")
                .addBpmnModel("请假.bpmn", bpmnModel)
                .deploy();


        //测试-------> 查询动态生成的BpmnModel对应的流程是否正确;
        BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
        byte[] bytes = xmlConverter.convertToXML(bpmnModel);
        System.out.println(new String(bytes));

    }

}
